<style lang="scss" scoped></style>

<template>
    <div class="app-container">
        <el-card class="card">
            <el-form :model="queryParams" inline>
                <el-form-item label="用户昵称">
                    <el-input v-model="queryParams.name" placeholder="请输入用户昵称"></el-input>
                </el-form-item>
                <el-form-item label="用户账号">
                    <el-input v-model="queryParams.username" placeholder="请输入用户账号"></el-input>
                </el-form-item>
                <el-form-item label="身份">
                    <el-select v-model="queryParams.role_id" placeholder="请选择身份" style="width: 100%;">
                        <el-option v-for="role in roleList" :key="role.id" :label="role.name" :value="role.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label-width="15px">
                    <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                    <el-button type="info" icon="el-icon-refresh-right" @click="handleRefresh">刷新</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card class="table">
            <div class="table-buttons">
                <el-button v-waves type="primary" icon="el-icon-plus" @click="handleShowAlert(true)" v-permission="['sys:account:add']">添加</el-button>
                <el-button v-waves type="danger" icon="el-icon-delete" :disabled="isForbidden" @click="handleMultipleRemove"
                    v-permission="['sys:account:remove']">删除</el-button>
            </div>
            <el-table v-loading="loading" :data="list" @selection-change="selectionChange" border>
                <el-table-column align="center" type="selection" />
                <el-table-column align="center" prop="sort" label="排序" width="60px" />
                <el-table-column prop="name" label="用户昵称" show-overflow-tooltip />
                <el-table-column prop="username" label="用户账号" show-overflow-tooltip />
                <el-table-column label="身份" v-slot="{ row }" show-overflow-tooltip>
                    <span class="empty">{{ row.roles_name && row.roles_name.join('，') }}</span>
                </el-table-column>
                <el-table-column v-slot="{ row }" align="center" label="操作" width="220px">
                    <template>
                        <el-button type="text" icon="el-icon-refresh" size="small"
                            @click="handleShowdialogEditPasswordVisible(row.id)">修改密码</el-button>
                        <el-button type="text" icon="el-icon-edit" size="small"
                            @click="handleShowAlert(false, row)"  v-permission="['sys:account:edit']">编辑</el-button>
                        <el-button type="text" icon="el-icon-delete" size="small"
                            @click="handleSingleRemove(row.id)" v-permission="['sys:account:remove']">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <Pagination v-show="total > 0" :total="total" :page.sync="queryParams.page_number"
                :limit.sync="queryParams.page_size" @pagination="getList" />
        </el-card>
        <el-dialog :title="isAdd ? '新增账号' : '编辑账号'" :visible.sync="dialogVisible" top="20vh" width="500px"
            :before-close="closeClearFormData" destroy-on-close>
            <el-form :model="formData" label-width="100px" size="small" ref="ruleForm" :rules="rules">
                <el-form-item label="用户昵称" prop="name">
                    <el-input v-model="formData.name" placeholder="请输入用户昵称" />
                </el-form-item>
                <el-form-item label="用户账号" prop="username">
                    <el-input v-model="formData.username" placeholder="请输入用户账号" />
                </el-form-item>
                <el-form-item label="身份" prop="roles_ids">
                    <el-select v-model="formData.roles_ids" multiple collapse-tags>
                        <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input-number v-model="formData.sort" :min="0" placeholder="请选则排序" controls-position="right" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="closeClearFormData">取 消</el-button>
                <el-button type="primary" @click="isAdd ? submitAdd() : submitEdit()">确 定</el-button>
            </template>
        </el-dialog>
        <el-dialog title="修改密码" :visible.sync="dialogEditPasswordVisible" top="20vh" width="500px" destroy-on-close
            @close="newPasswordFormData = {}">
            <el-input v-model="newPasswordFormData.new_password" @keyup.native.enter="submitEditPassword"
                ref="inputRef"></el-input>
            <template #footer>
                <el-button @click="dialogEditPasswordVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitEditPassword">确 定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import '@/assets/css/clear-card.css'
import waves from '@/directive/waves/index.js' // 水波纹指令
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { getList, add, edit, remove, editPassword } from '@/api/system/account.js'
import { getList as getRoleList } from '@/api/system/role.js'
export default {
    name: 'User',
    components: { Pagination },
    directives: { waves },
    data() {
        return {
            // 查询参数
            queryParams: {
                // 一页显示多少条数据
                page_size: 10,
                // 当前页码数
                page_number: 1
            },
            // 列表数据
            list: [],
            // 数据条数
            total: 0,
            // 数据加载中控件
            loading: true,
            // 当前弹出窗口是添加或者修改，true：添加；false：修改
            isAdd: true,
            // 添加、修改弹窗控件
            dialogVisible: false,
            // 新增 | 编辑，数据表单
            formData: {
                sort: 0
            },
            // 添加修改接口节流阀门
            throttle: true,
            // 设置表单验证规则
            rules: {
                name: [{
                    required: true, message: '请输入用户昵称', trigger: ['blur', 'change']
                }],
                username: [{
                    required: true, message: '请输入用户账号', trigger: ['blur', 'change']
                }],
                roles_ids: [{
                    required: true, message: '请选择身份', trigger: ['blur']
                }],
                sort: [{
                    required: true, message: '请选择排序', trigger: ['blur', 'change']
                }]
            },
            // 已选中的 id 数组
            ids: [],
            // 当前是否禁用删除按钮，当有复选框选中时，才不禁用
            isForbidden: true,
            // 身份下拉框列表数据
            roleList: [],
            // 修改密码弹窗控件
            dialogEditPasswordVisible: false,
            // 修改密码数据表单
            newPasswordFormData: {}
        }
    },
    created() {
        this.getList()
        this.getRoleList()
    },
    methods: {
        submitEditPassword() {
            const regex = /^(?!.*\s).{5,20}$/
            const newPassword = this.newPasswordFormData.new_password
            if (!(regex.test(newPassword) && newPassword)) return this.$message.error('请输入一个5到20位的密码，并且不包含空格')
            if (this.throttle) {
                this.throttle = false
                const form = { ...this.newPasswordFormData }
                editPassword(form).then(({ message }) => {
                    this.$message.success(message)
                    this.getList()
                    this.dialogEditPasswordVisible = false
                }).finally(() => {
                    this.throttle = true
                })
            }
        },
        // 显示修改密码弹窗
        handleShowdialogEditPasswordVisible(id) {
            this.$set(this.newPasswordFormData, 'id', id)
            this.dialogEditPasswordVisible = true
            this.$nextTick(() => {
                this.$refs.inputRef.focus()
            })
        },
        submitEdit() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid && this.throttle) {
                    this.throttle = false
                    const form = { ...this.formData }
                    edit(form).then(({ message }) => {
                        this.$message.success(message)
                        this.getList()
                        this.closeClearFormData()
                    }).finally(() => {
                        this.throttle = true
                    })
                }
            })
        },
        // 调用删除接口
        submitRemove(ids) {
            remove(ids).then(({ message }) => {
                this.$message.success(message)
                this.getList()
            })
        },
        handleMultipleRemove() {
            this.$confirm('是否删除选中的数据', '提醒', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const ids = [...this.ids]
                this.submitRemove(ids)
            }).catch(() => {
                this.$message.info('已取消')
            })
        },
        // 单选删除
        handleSingleRemove(id) {
            this.$confirm('是否删除该条数据', '提醒', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const ids = [id]
                this.submitRemove(ids)
            }).catch(() => {
                this.$message.info('已取消')
            })
        },
        // 调用接口，添加列表内容
        submitAdd() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid && this.throttle) {
                    this.throttle = false
                    const form = { ...this.formData }
                    add(form).then(({ message }) => {
                        this.$message.success(message)
                        this.getList()
                        this.closeClearFormData()
                    }).finally(() => {
                        this.throttle = true
                    })
                }
            })
        },
        // 弹出添加或者修改弹窗
        handleShowAlert(alertTypeBool, row) {
            // 弹出弹窗层
            this.dialogVisible = true
            // 设置弹窗类型。true：添加；false：修改；
            this.isAdd = alertTypeBool
            // 如果为修改弹窗，回显字段值并渲染页面
            if (!this.isAdd) {
                this.$set(this.formData, 'id', row.id)
                this.$set(this.formData, 'name', row.name)
                this.$set(this.formData, 'username', row.username)
                this.$set(this.formData, 'roles_ids', row.roles_ids)
                this.$set(this.formData, 'sort', row.sort)
            }
        },
        // 收集选中的 ids
        selectionChange(val) {
            this.ids = val.map(item => item.id)
            this.isForbidden = Boolean(this.ids.length === 0)
        },
        // 监听搜索按钮点击事件
        handleSearch() {
            this.queryParams.page_number = 1
            this.getList()
        },
        // 监听刷新按钮点击事件
        handleRefresh() {
            this.$data.queryParams = this.$options.data().queryParams
            this.getList()
        },
        // 关闭弹窗时，需要清楚所有的form表单的数据
        closeClearFormData() {
            this.$data.formData = this.$options.data().formData
            this.dialogVisible = false
        },
        async getRoleList() {
            const query = {
                page_size: 99999,
                page_number: 1
            }
            const { data } = await getRoleList(query)
            this.roleList = data
        },
        // 获取列表信息
        async getList() {
            this.loading = true
            const query = { ...this.queryParams }
            const { data, total } = await getList(query)
            this.list = data
            this.total = total
            this.loading = false
        }
    }
}
</script>
